package com.lagou.session;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.*;
import java.util.List;

import static com.lagou.pojo.SqlCommandType.*;

/**
 * 默认sqlSession实现类
 *
 * @author Tengfei.Wang
 * @date 26/8/2020
 */
@Slf4j
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private final Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    public <T> List<T> selectList(String statementId, Object params) {
        List<Object> query = executor.query(configuration, getMapperStatement(statementId), params);
        return (List<T>) query;
    }

    public <T> T selectOne(String statementId, Object params) {
        List<Object> objects = this.selectList(statementId, params);
        if (objects != null && objects.size() > 1) {
            throw new RuntimeException("查询结果不唯一");
        }
        if (objects == null || objects.size() <= 0) {
            return (T) null;
        }
        return (T) objects.get(0);
    }

    public <T> void insert(String statementId, Object params) {
        executor.update(configuration, getMapperStatement(statementId), params);
    }

    public <T> void update(String statementId, Object params) {
        executor.update(configuration, getMapperStatement(statementId), params);
    }

    public <T> void delete(String statementId, Object params) {
        executor.update(configuration, getMapperStatement(statementId), params);
    }

    public <T> T getMapper(Class<T> t) {
        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{t}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //代理对象的方法名
                String name = method.getName();
                //代理对象的类名
                String className = method.getDeclaringClass().getName();
                //statement id
                String statementId = String.format("%s.%s", className, name);

                MapperStatement mappedStatement = configuration.getStatementMap().get(statementId);
                if (mappedStatement == null) {
                    log.error("mappedStatement {} is not found", statementId);
                    throw new RuntimeException("找不到需要执行的方法");
                }
                String sql = mappedStatement.getSql();
                //根据sql语句包含的操作，来指向对象的方法
                if (sql.toLowerCase().contains(SELECT)) {
                    Type returnType = method.getGenericReturnType();
                    if (returnType instanceof ParameterizedType) {
                        return selectList(statementId, args);
                    }
                    return selectOne(statementId, args);
                }
                if (sql.toLowerCase().contains(INSERT)) {
                    insert(statementId, args);
                }
                if (sql.toLowerCase().contains(UPDATE)) {
                    update(statementId, args);
                }
                if (sql.toLowerCase().contains(DELETE)) {
                    delete(statementId, args);
                }
                return null;
            }
        });
        return (T) proxyInstance;
    }

    public MapperStatement getMapperStatement(String statementId) {
        MapperStatement mapperStatement = configuration.getStatementMap().get(statementId);
        if (mapperStatement == null) {
            log.error("cant not found statement: {}", statementId);
            throw new RuntimeException("无法找到需要执行的方法");
        }
        return mapperStatement;
    }
}
